package cn.sdormitory.service.impl;

import cn.hutool.json.JSONUtil;
import cn.sdormitory.basedata.dao.BStudentDao;
import cn.sdormitory.basedata.entity.BStudent;
import cn.sdormitory.common.utils.SysUserUtils;
import cn.sdormitory.service.AppWeChatService;
import cn.sdormitory.sys.dao.SysUserDao;
import cn.sdormitory.sys.entity.SysUser;
import cn.sdormitory.utils.HttpUtils;
import cn.sdormitory.utils.WxEncryptedDataDeCode;
import cn.sdormitory.utils.wx.WeChatMessageSendUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

/**
 * @author: lx
 * @date: 2023/11/15 11:40
 * @description:
 */
@Slf4j
@Service
public class AppWeChatServiceImpl implements AppWeChatService {

    @Resource
    SysUserDao sysUserDao;

    @Autowired
    BStudentDao bStudentDao;
    
    @Resource
    RestTemplate restTemplate;

    @Autowired
    WeChatMessageSendUtil weChatMessageSendUtil;

    @Override
    public Integer saveOpenId(String code,String role) {
        Map<String, String> map = weChatMessageSendUtil.getOpenId(code);
        if(map != null && map.size() > 0){
            if(role.equals("student")){
                BStudent student = SysUserUtils.getStudentUser();
                student.setWxOpenId(map.get("openid"));
                return bStudentDao.updateById(student);
            }else {
                SysUser sysUser = SysUserUtils.getSysUser();
                sysUser.setWxOpenId(map.get("openid"));
                return sysUserDao.updateById(sysUser);
            }
        }
        return -1;
    }
    
    @Override
    public Map<String, String> getWxOpenId(Map<String, String> paramMap)  throws IOException{
        String jsonStr = JSON.toJSONString(getOpenId(paramMap));
        getWxUserInfo(jsonStr);
        return JSON.parseObject(jsonStr,Map.class);
    }
    
    @Override
    public JSONObject getPhone(Map<String, String> paramMap) {
        String encryptedData = paramMap.get("encryptedData");
        String iv = paramMap.get("iv");
//        String userEncryptedData = paramMap.get("userEncryptedData");
//        String userIv = paramMap.get("userIv");
        String session_key = paramMap.get("session_key");
//        com.alibaba.fastjson.JSONObject userInfo1 = WxEncryptedDataDeCode.getUserInfo(userEncryptedData, session_key, userIv);
        com.alibaba.fastjson.JSONObject userInfo = WxEncryptedDataDeCode.getUserInfo(encryptedData, session_key, iv);
        //查询用户手机号是否存在，如果存在则查询手机号对应的推荐码
//        LambdaQueryWrapper<TUserInfo> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(TUserInfo::getUserMobile,userInfo.get("phoneNumber"));
//        TUserInfo tUserInfo = userInfoMapper.selectOne(wrapper);
//        if(tUserInfo!=null){
//            userInfo.put("code",tUserInfo.getRecommendedUserCode());
//        }
//
        System.out.println(userInfo);
        return userInfo;
    }
    
    private JSONObject getOpenId(Map<String, String> paramMap) {
        StringBuffer params = new StringBuffer();
//        params.append("appid=").append("wxc82827b153d4040a");
//        params.append("&secret=").append("da841b7440fdf4d38f591031416f9103");
        params.append("appid=").append("wxa1e5577fa5b381ff");
        params.append("&secret=").append("543703f246d2ad0c1fe6d8eb1db0b78a");
        params.append("&grant_type=").append("authorization_code");
        params.append("&js_code=").append(paramMap.get("code"));
        String result = HttpUtils.sendGet(
                "https://api.weixin.qq.com/sns/jscode2session", params.toString());
        String openid = "";
        JSONObject jsonObject =null;
        if (result != null) {
            jsonObject = JSONObject.parseObject(result);
        }
        return jsonObject;
    }
    
    private void getWxUserInfo(String openId) throws IOException {
        String token = this.getAccessToken();
        //设置查询参数与请求url
        //`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${secret}&code=${this.code}&grant_type=authorization_code`;
        MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();
//        queryParams.add("access_token", token);
        queryParams.add("openid", openId);
        queryParams.add("lang", "zh_CN");
        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/component/api_get_authorizer_info?access_token="+token;
        UriComponentsBuilder tokenBuilder = UriComponentsBuilder.fromHttpUrl(tokenUrl).queryParams(queryParams);
        //获取token
        String tokenResult = restTemplate.getForObject(tokenBuilder.toUriString(), String.class);
        cn.hutool.json.JSONObject tokenObject = JSONUtil.parseObj(tokenResult);
    }
    
    private String getAccessToken() throws ClientProtocolException, IOException {
//        String appid="wxc82827b153d4040a";
//        String secret="da841b7440fdf4d38f591031416f9103";
        
        String appid="wxa1e5577fa5b381ff";
        String secret="543703f246d2ad0c1fe6d8eb1db0b78a";
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+secret;
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpResponse res = httpClient.execute(httpGet);
        HttpEntity entity = res.getEntity();
        String result = EntityUtils.toString(entity, "UTF-8");
        JSONObject jsons = JSONObject.parseObject(result);
//			String expires_in = jsons.getString("expires_in");
        String access_token = jsons.getString("access_token");
        //缓存
//			String access_token = null;
//			if(Integer.parseInt(expires_in)==7200){
//				//ok
//				access_token = jsons.getString("access_token");
//				redisUtil.set("small_accesstoken", access_token, Long.valueOf(expires_in));
//			}
        return access_token;
        
    }
    
}
